package com.func.domain.activity.service.armory;

import com.func.domain.activity.model.entity.ActivitySkuEntity;
import com.func.domain.activity.repository.IActivityRepository;
import com.func.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * ActivityArmory
 * </p>
 *
 * @author Simon
 * @version 2025.03.13.1.0.0
 * @description
 * @since 2025-03-13
 */

@Slf4j
@Service
public class ActivityArmory implements IActivityArmory, IActivityDispatch {
    @Resource
    protected IActivityRepository activityRepository;
    @Override
    public boolean assembleActivitySku(Long sku) {
        // 1. 预热活动SKU库存数量
        ActivitySkuEntity activitySkuEntity = activityRepository.queryActivitySku(sku);
        if (null == activitySkuEntity) {
            log.error("库存预热失败, 传入的sku不存在, 请检查数据库中的配置");
            return false;
        }
        cacheActivitySkuStock(sku, activitySkuEntity.getStockCount());

        // 2. 预热活动 [查询时预热到缓存中]
        activityRepository.queryRaffleActivityByActivityId(activitySkuEntity.getActivityId());

        // 3. 预热活动次数 [查询时预热到缓存中]
        activityRepository.queryActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());

        return true;
    }

    /**
     * 根据活动ID装配所有的sku商品
     * @param activityId 活动ID
     * @return 装配结果
     */
    @Override
    public boolean assembleActivitySkuByActivityId(Long activityId) {
        List<ActivitySkuEntity> activitySkuEntities =  activityRepository.queryActivitySkuListByActivityId(activityId);
        for (ActivitySkuEntity activitySkuEntity : activitySkuEntities) {
            cacheActivitySkuStock(activitySkuEntity.getSku(), activitySkuEntity.getStockCount());
            // 预热活动次数 [查询时预热到缓存]
            activityRepository.queryActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());
        }
        // 预热活动, [查询时预热]
        activityRepository.queryRaffleActivityByActivityId(activityId);

        return true;
    }

    /**
     * 将这组sku和库存数量加载进redis中
     * @param sku sku编号
     * @param stockCount 库存数量
     */
    private void cacheActivitySkuStock(Long sku, Integer stockCount) {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY + sku;
        activityRepository.cacheActivitySkuStock(cacheKey, stockCount);
    }

    @Override
    public boolean subtractionActivitySkuStock(Long sku, Date endDateTime) {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY + sku;
        return activityRepository.subtractionActivitySkuStock(sku, cacheKey, endDateTime);
    }
}
